package com.vichat.common.rudp.thread;

import com.vichat.common.rudp.RudpDataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.DatagramPacket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class RudpReceiveManager extends Thread {
    public static ExecutorService receivExec = Executors.newFixedThreadPool(500);
    private static transient Logger logger = LoggerFactory.getLogger(RudpReceiveManager.class);

    public RudpReceiveManager() {

    }

    public void run() {

        while (true) {
            try {
                long startIme = System.currentTimeMillis();
                byte[] buffer = new byte[1024]; // 缓冲区  
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                long midtime = System.currentTimeMillis() - startIme;
                try {
                    RudpDataUtil.getServerSocket().receive(packet);
                } catch (Exception e) {
                    logger.error("报文接收失败", e);
                    //sleep(200);
                    continue;
                    //logger.error("报文接收失败",e);
                }
                if (packet.getLength() <= 0) {
                    logger.error("数据为空");
                    //sleep(200);
                    continue;
                }
                if (packet.getAddress() == null) {
                    logger.error("对端地址为空");
                    //sleep(200);
                    continue;
                }


                //logger.error("数据接收成功"+packet.getAddress().getHostAddress()+":"+packet.getPort()+";"+packet.getLength()+";"+new String(packet.getData()));
                receivExec.execute(new RudpReceiveThread(packet));
                long costtime = System.currentTimeMillis() - startIme;
                if (costtime > 50) {
                    logger.error("!!!!!!!!!!!!接收数据出错:" + costtime + "," + midtime);
                }
            } catch (Exception e) {
                logger.error("单个报文处理失败", e);
            }
        }

    }

}
